package com.baozi.order.service;

import com.baozi.order.client.ProductClient;
import com.baozi.order.dto.CartDto;
import com.baozi.order.dto.OrderDto;
import com.baozi.order.entity.OrderDetail;
import com.baozi.order.entity.OrderMaster;
import com.baozi.order.entity.product;
import com.baozi.order.enums.OrderStatusEnum;
import com.baozi.order.enums.PayStatusEnum;
import com.baozi.order.repository.OrderDetailRepository;
import com.baozi.order.repository.OrderMasterRepository;
import com.baozi.order.utlis.KeyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderService {

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private ProductClient productClient;

    @Transactional
    public OrderDto add(OrderDto dto) {

       String orerId= KeyUtil.genUniqueKey();

        //查询商品信息
        List<String> productIds=dto.getList().stream()
              .map(OrderDetail::getProductId)
              .collect(Collectors.toList());
        List<product> productList=productClient.getProductList(productIds);

        //计算总价
        //初始化
        BigDecimal orderCount=new BigDecimal(0);
        for(OrderDetail order:dto.getList()){
            for(product pro:productList){
                if(pro.getProductId().equals(order.getProductId())){
                    orderCount=pro.getProductPrice()
                            .multiply(new BigDecimal(order.getProductQuantity()))
                            .add(orderCount);
                    BeanUtils.copyProperties(pro,order);
                    order.setOrderId(orerId);
                    order.setDetailId(KeyUtil.genUniqueKey());
                    //订单详情入库
                    orderDetailRepository.save(order);
                }
            }
        }
        //扣库存
        List<CartDto> cartDtoList=dto.getList().stream()
                .map(e->new CartDto(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productClient.deleteStocke(cartDtoList);

        //订单入库
        OrderMaster orderMaster = new OrderMaster();
        dto.setOrderId(orerId);
        BeanUtils.copyProperties(dto, orderMaster);
        orderMaster.setOrderAmount(orderCount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WITE.getCode());
        orderMasterRepository.save(orderMaster);
        return dto;
    }

}
